package com.slofzx.nuoda.evaluation.param.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.slofzx.nuoda.common.exception.ServiceException;
import com.slofzx.nuoda.common.util.IdGen;
import com.slofzx.nuoda.common.vo.SysUserVO;
import com.slofzx.nuoda.evaluation.param.entity.CommonParamVersion;
import com.slofzx.nuoda.evaluation.param.dto.CommonParamVersionDTO;
import com.slofzx.nuoda.evaluation.param.enums.ParamVersionStateEnum;
import com.slofzx.nuoda.evaluation.param.enums.PermissionEnum;
import com.slofzx.nuoda.evaluation.param.service.CommonParamVersionDataService;
import com.slofzx.nuoda.evaluation.param.vo.CommonParamVersionVO;
import com.slofzx.nuoda.evaluation.param.dao.CommonParamVersionDAO;
import com.slofzx.nuoda.evaluation.param.service.CommonParamVersionService;
import com.slofzx.nuoda.evaluation.project.util.BusiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import com.slofzx.nuoda.common.enums.CommonResultEnum;
import com.slofzx.nuoda.common.enums.ServiceResult;
import com.slofzx.nuoda.common.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 公共参数版本信息服务实现类
 *
 * @author nuoda
 * @since 2023-10-17 16:02:20
 */
@Service("commonParamVersionService")
public class CommonParamVersionServiceImpl extends BaseServiceImpl implements CommonParamVersionService {

    @Resource
    private CommonParamVersionDAO commonParamVersionDAO;
    @Autowired
    private CommonParamVersionDataService commonParamVersionDataService;

    /**
     * 将数据表数据转换为返回数据类型
     *
     * @param entity 数据表对应类
     * @return 实例对象
     */
    protected CommonParamVersionVO parseEntity2VO(CommonParamVersion entity) {
        CommonParamVersionVO vo = new CommonParamVersionVO();
        vo.setId(entity.getId());
        vo.setName(entity.getName());
        vo.setState(entity.getState());
        vo.setPublishTime(entity.getPublishTime());
        vo.setPublishUser(entity.getPublishUser());
        vo.setRemark(entity.getRemark());
        vo.setCreateTime(entity.getCreateTime());
        vo.setCreateUser(entity.getCreateUser());
        return vo;
    }

    /**
     * 将数据传递类转换为数据表数据类
     *
     * @param dto 数据传递类实例
     * @return 实例对象
     */
    protected CommonParamVersion parseDTO2Entity(CommonParamVersionDTO dto) {
        CommonParamVersion entity = new CommonParamVersion();
        entity.setId(dto.getId());
        entity.setName(dto.getName());
        entity.setState(dto.getState());
        entity.setPublishUser(dto.getPublishUser());
        entity.setRemark(dto.getRemark());
        return entity;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public CommonParamVersionVO queryById(String id) {
        CommonParamVersion entity = this.commonParamVersionDAO.selectById(id);
        if (entity == null) {
            return null;
        }
        return parseEntity2VO(entity);
    }

    /**
     * 查询多条数据
     *
     * @param dto 数据传递类实例对象
     * @return 对象列表
     */
    @Override
    public List<CommonParamVersionVO> queryList(CommonParamVersionDTO dto) {
        //mybatis-plus 写法示例
        //IPage<CommonParamVersion> pageResult = this.evaModelDAO.selectPage(new Page<>(dto.getPageNo(),dto.getPageSize()),null);
        //List<CommonParamVersion> dataList = pageResult.getRecords();
        //dto.setCount((int) pageResult.getTotal());
        List<CommonParamVersion> dataList = this.commonParamVersionDAO.queryList(dto);
        if (null == dataList || dataList.isEmpty()) {
            return Collections.emptyList();
        }
        List<CommonParamVersionVO> resultList = new ArrayList(dataList.size());
        for (CommonParamVersion item : dataList) {
            CommonParamVersionVO vo = parseEntity2VO(item);
            resultList.add(vo);
        }
        // TODO 添加其他关联查询数据
        return resultList;
    }

    /**
     * 新增数据
     *
     * @param dto 实例对象
     * @return 操作结果
     */
    @Override
    public ServiceResult create(CommonParamVersionDTO dto) {
        // TODO 添加校验逻辑
        CommonParamVersion entity = parseDTO2Entity(dto);
        if (StringUtils.isNotEmpty(dto.getName())) {
            checkDuplicateName(dto.getName(), null);
        }
        entity.setState(ParamVersionStateEnum.INIT.getId());
        preInsert(entity);
        this.commonParamVersionDAO.insert(entity);
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 修改数据
     *
     * @param dto 实例对象
     * @return 操作结果
     */
    @Override
    public ServiceResult update(CommonParamVersionDTO dto) {
        String id = dto.getId();
        if (StringUtils.isEmpty(id)) {
            return CommonResultEnum.NOT_EXIST;
        }
        CommonParamVersion entity = this.commonParamVersionDAO.selectById(id);
        if (StringUtils.isNotEmpty(dto.getName())) {
            checkDuplicateName(dto.getName(), dto.getId());
        }
        if (entity == null) {
            return CommonResultEnum.NOT_EXIST;
        }
        // TODO 添加其他校验逻辑，如数据权限

        entity.setName(dto.getName());
        entity.setState(dto.getState());
        entity.setPublishUser(dto.getPublishUser());
        entity.setRemark(dto.getRemark());
        this.commonParamVersionDAO.updateById(entity);
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 操作结果
     */
    @Override
    @Transactional
    public ServiceResult deleteById(String id) {
        CommonParamVersion version = commonParamVersionDAO.selectById(id);
        if(version == null) {
            return CommonResultEnum.NOT_EXIST;
        }
        //已发布版本不可删除
        ParamVersionStateEnum stateEnum = ParamVersionStateEnum.getEnum(version.getState());
//        if(stateEnum == ParamVersionStateEnum.PUBLISH) {
//            return CommonResultEnum.PERMISSION_DENY;
//        }
        //校验组织机构
        SysUserVO userVO = getUser();
        // 校验是否有删除公共参数的权限
        //BusiUtil.checkPermission(userVO, PermissionEnum.COMMON_PARAM_DELETE);
        ServiceResult result = commonParamVersionDataService.delete(id);
        if(result!=CommonResultEnum.SUCCESS) {
            throw new ServiceException("删除关联数据异常，删除失败","删除版本关联数据异常，删除失败",id);
        }
        this.commonParamVersionDAO.deleteById(id);
        return CommonResultEnum.SUCCESS;
    }

    @Override
    public ServiceResult publish(CommonParamVersionDTO dto) {
        CommonParamVersion version = commonParamVersionDAO.selectById(dto.getId());
        if(version == null) {
            return CommonResultEnum.NOT_EXIST;
        }
        if(ParamVersionStateEnum.getEnum(version.getState()) == ParamVersionStateEnum.PUBLISH) {
            return CommonResultEnum.PERMISSION_DENY;
        }
        version.setState(ParamVersionStateEnum.PUBLISH.getId());
        version.setPublishTime(new Date());
        version.setPublishUser(getUserId());
        commonParamVersionDAO.updateById(version);
        return CommonResultEnum.SUCCESS;
    }

    @Override
    public ServiceResult unPublish(CommonParamVersionDTO dto) {
        CommonParamVersion version = commonParamVersionDAO.selectById(dto.getId());
        if(version == null) {
            return CommonResultEnum.NOT_EXIST;
        }
        if(ParamVersionStateEnum.getEnum(version.getState()) == ParamVersionStateEnum.INIT) {
            return CommonResultEnum.PERMISSION_DENY;
        }
        version.setState(ParamVersionStateEnum.INIT.getId());
        version.setPublishTime(null);
        version.setPublishUser(null);
        commonParamVersionDAO.updateById(version);
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 检查项目名称是否重复
     * @param name
     */
    private void checkDuplicateName(String name,String id) {
        LambdaQueryWrapper<CommonParamVersion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonParamVersion::getName, name);
        if (StringUtils.isNotEmpty(id)) {
            queryWrapper.ne(CommonParamVersion::getId, id);
        }
        final Long count = commonParamVersionDAO.selectCount(queryWrapper);
        if (count>0) {
            throw new ServiceException("公共参数名称重复，请修改后提交", null,null);
        }
    }

    @Override
    @Transactional
    public ServiceResult copy(CommonParamVersionDTO dto) {
        final String id = dto.getId();
        CommonParamVersion version = commonParamVersionDAO.selectById(id);
        if(version == null) {
            return CommonResultEnum.NOT_EXIST;
        }
        if (StringUtils.isNotEmpty(dto.getName())) {
            checkDuplicateName(dto.getName(), null);
        }
        final SysUserVO user = getUser();
//        if (!user.isAdmin()&&!user.getId().equals(version.getCreateUser())) {
//            throw new ServiceException("只允许创建人复制","只允许创建人复制",null);
//        }
        final String uuid = IdGen.uuid();
        commonParamVersionDataService.copy(id,uuid);
        //复制版本号
        final CommonParamVersion deepCopy = new CommonParamVersion();
        deepCopy.setId(uuid);
        deepCopy.setState(ParamVersionStateEnum.INIT.getId());
        deepCopy.setCreateTime(new Date());
        deepCopy.setCreateUser(user.getId());
        deepCopy.setName(dto.getName());
        deepCopy.setRemark(dto.getRemark());
        commonParamVersionDAO.insert(deepCopy);
        return CommonResultEnum.SUCCESS;
    }
}
